package com.nowcoder.community.controller;

import com.nowcoder.community.service.AlphaService;
import com.nowcoder.community.utils.CommunityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping(path = "/alpha")
public class HelloController {

    @Autowired
    private AlphaService alphaService;

    @RequestMapping(value = "/")
    @ResponseBody
    public String test() {
        return "123";
    }


    @RequestMapping(value = "/data")
    @ResponseBody
    public String test1() {
        return alphaService.testService();
    }


    @RequestMapping(value = "/hello")
    public void http(HttpServletRequest request, HttpServletResponse response) {
        //获取请求数据
        //请求方法，请求路径
        System.out.println(request.getMethod());
        System.out.println(request.getServletPath());
        //打印所有请求头的参数名称和参数值
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String names = headerNames.nextElement();
            String value = request.getHeader(names);
            System.out.println(names + ": " + value);
        }
        //打印请求参数code
        System.out.println(request.getParameter("code"));

        //返回响应数据
        response.setContentType("text/html;charset=utf-8");
        //直接输出到页面上

        try (
                PrintWriter writer = response.getWriter();
        ) {
            writer.print("<h1>123</h1>");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //get请求 两种传参方式
    // /student?current=1&limit=15
    @RequestMapping(path = "/student", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@RequestParam(name = "current", required = false, defaultValue = "1") int current,
                             @RequestParam(name = "limit", required = false, defaultValue = "15") int limit) {
        //有时候请求参数不一定有，所以需要利用@RequestParam处理一下
        System.out.println(current);
        System.out.println(limit);

        return "student";
    }

    // /stu/{id}
    @RequestMapping(path = "/stu")
    @ResponseBody
    public String getStu(@PathVariable(value = "id") int id) {
        System.out.println(id);
        return "stu";
    }

    //响应post请求
    @RequestMapping(value = "/student", method = RequestMethod.POST)
    @ResponseBody
    public String addStudent(String name, int age) {
        return "success";
    }


    //响应动态html数据
    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
    public ModelAndView test2() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name", "mwx");
        modelAndView.addObject("age", "25");
        modelAndView.setViewName("/html/teacher");
        return modelAndView;
    }


    @RequestMapping(path = "/school", method = RequestMethod.GET)
    public String test9(Model model){
        model.addAttribute("name","qwe");
        model.addAttribute("age","123");
        return "/html/teacher";
    }


    // 响应JSON数据（异步请求）
    // Java对象->json对象->js对象
    @RequestMapping(value = "/emp",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> test8(){
        Map<String, Object> map = new HashMap<>();
        map.put("name","zhangsan");
        map.put("age","25");
        map.put("salary","25000");
        return map;
    }

    //多个java对象
    @RequestMapping(value = "/emps",method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> emps(){
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name","zhangsan");
        map.put("age","25");
        map.put("salary","25000");
        list.add(map);

        map = new HashMap<>();
        map.put("name","lisi");
        map.put("age","26");
        map.put("salary","45000");
        list.add(map);

        map = new HashMap<>();
        map.put("name","wangwu");
        map.put("age","27");
        map.put("salary","55000");
        list.add(map);

        return list;
    }

    //cookies示例
    //浏览器首次访问，服务端创建一个cookies，cookies自动存入response的头部
    @RequestMapping(path = "/cookie/set",method = RequestMethod.GET)
    @ResponseBody
    public String setCookies(HttpServletResponse response){
        //创建cookies
        Cookie cookie = new Cookie("my_cookies", CommunityUtil.generateUUID());
        //设置cookie生效的范围
        cookie.setPath("/community/alpha");
        //设置cookies的生存时间
        cookie.setMaxAge(60 * 10);
        //发送cookies
        response.addCookie(cookie);
        return "set cookies";
    }

    @RequestMapping(path = "/cookie/get",method = RequestMethod.GET)
    @ResponseBody
    public String getCookies(@CookieValue("my_cookies") String cookies){
        System.out.println(cookies);
        return "get cookies";
    }

    @RequestMapping(path = "/session/set",method = RequestMethod.GET)
    @ResponseBody
    public String setSession(HttpSession session){
        session.setAttribute("id",111);
        session.setAttribute("name","test");
        return "setSession";
    }

    @RequestMapping(path = "/session/get", method = RequestMethod.GET)
    @ResponseBody
    public String getSession(HttpSession session) {
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("name"));
        return "get session";
    }

    // ajax示例
    @RequestMapping(path = "/ajax", method = RequestMethod.POST)
    @ResponseBody
    public String testAjax(@RequestParam(value = "name" ,required = false) String name,@RequestParam(value = "age" ,required = false) Integer age) {
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0, "操作成功!");
    }



}